package com.jt.demo01_CGLIB.proxy;

import org.springframework.cglib.proxy.Callback;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;


public class CglibProxy {
//动态代理机制--CGLIB
    //特点代理对象是目标对象的子类
    public static Object getObject(Object target){
        //创建增强器对象
        Enhancer enhancer = new Enhancer();
        //设置父级
        enhancer.setSuperclass(target.getClass());
        enhancer.setCallback(getMethodInterceptor());
        return enhancer.create();
    }

    public static MethodInterceptor getMethodInterceptor(){

        return new MethodInterceptor() {
            @Override
            public Object intercept(Object obj, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                System.out.println("数据库事务开始");
                //执行父类的方法
                Object proxy = methodProxy.invokeSuper(obj,objects);
                System.out.println("数据库事务提交");
                return proxy;
            }
        };
    }

}